import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginApi, userInfoApi } from '@/api/user'

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref('')
    const userInfo = ref({})
    // 登录
    const login = async (data) => {
      // 设置token
      const res = await loginApi(data)
      token.value = res.data
    }
    // 登出
    const logout = () => {
      token.value = ''
      userInfo.value = ''
    }

    // 设置用户信息
    const setUserInfo = async () => {
      // 设置userInfo
      const res = await userInfoApi()
      userInfo.value = res.data
    }

    return {
      token,
      userInfo,
      login,
      logout,
      setUserInfo
    }
  },
  {
    persist: {
      paths: ['token']
    }
  }
)
